package com.mxsoft.ssmdemo.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mxsoft.ssmdemo.model.Foo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextHierarchy({
        @ContextConfiguration(name = "parent", locations = "classpath:spring/applicationContext.xml"),
        @ContextConfiguration(name = "child", locations = "file:src/main/webapp/WEB-INF/dispatcher-servlet.xml")
})
public class FooTestCase {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testInsert() throws Exception {
        Foo foo = new Foo();
        foo.setUsername("testusername");
        foo.setPassword("password");
        String mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/api/foo").contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(foo)))
                .andExpect(MockMvcResultMatchers.status().is(HttpStatus.OK.value())).andReturn().getResponse().getContentAsString();
        Foo foo1 = new ObjectMapper().readValue(mvcResult, Foo.class);
        Assert.assertNotNull(mvcResult);
        Assert.assertTrue(foo1.getUsername().equals(foo.getUsername()));
        Assert.assertTrue(foo1.getPassword().equals(foo.getPassword()));
    }
}
